package com.commons.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


/**
 * @author mis_wu
 * @date 2022/3/20 13:27
 */
@Configuration
public class RedisTemplateConfig {

    @Autowired
    public RedisTemplateConfig(RedisTemplate redisTemplate) {
        //1、创建jackson序列化方式
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        //2、创建Object mapper
        ObjectMapper objectMapper = new ObjectMapper();
        //3、允许访问对象中所有属性
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //4、转换json过程中保存类的信息
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        //5、设置key和value的序列化规划  key(String) value(String,list,Set,map)
        StringRedisSerializer hashKeySerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(hashKeySerializer);
        //6、jackson2JsonRedisSerializer就是json序列号规则
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        //6.1 设置hash类型key、value序列化方式
        redisTemplate.setHashKeySerializer(hashKeySerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        //7、工厂创建redisTemplate对象之后再进行配置
        redisTemplate.afterPropertiesSet();
    }
}
